﻿using log4net;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQMonitorService
{
    public class RabbitMQMonitorJob : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(RabbitMQMonitorJob));
        private readonly string USER_NAME = ConfigurationManager.AppSettings["UserName"];
        private readonly string PASSWORD = ConfigurationManager.AppSettings["Password"];
        private readonly string URL = ConfigurationManager.AppSettings["URL"];

        public Task Execute(IJobExecutionContext context)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{USER_NAME}:{PASSWORD}")));
                HttpContent httpContent = new StringContent("", Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Uri address = new Uri($"{URL}");
                try
                {
                    var response = client.GetAsync(address).Result.Content.ReadAsStringAsync().Result;//返回值
                    var res = JsonConvert.DeserializeObject<ResponseModel>(response);
                    if (res?.status != "ok")
                    {
                        _logger.Error($"【RabbitMQ异常】RabbitMQ健康检查返回状态异常！状态：{res?.status}");
                        //发短信
                        AliSendSms();
                    }
                    _logger.Info($"response:{res?.status}");
                }
                catch (Exception ex)
                {
                    _logger.Error($"【RabbitMQ异常】错误信息：{ex.Message}");
                    //发短信
                    AliSendSms();
                }
            }
            return Task.FromResult(true);
        }

        /// <summary>
        /// 发短信
        /// </summary>
        public void AliSendSms()
        {
            var (flag, msg) = SmsHelper.SendBatchSms();
            if (!flag) _logger.Error($"【阿里云短信发送异常】异常信息：{msg}");
        }
    }

    public class ResponseModel
    {
        public string status { get; set; }
    }
}
